package com.xindaoapp.happypet.shop.ui;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.util.SparseArrayCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.astuetz.PagerSlidingTabStrip;
import com.kmshack.newsstand.ScrollTabHolder;
import com.kmshack.newsstand.ScrollTabHolderFragment;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nineoldandroids.view.ViewHelper;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.socialize.sso.UMSsoHandler;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.BigViewPageActivity;
import com.xindaoapp.happypet.activity.MainActivity;
import com.xindaoapp.happypet.activity.ProductAddActivity;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.BigBanner;
import com.xindaoapp.happypet.bean.Product;
import com.xindaoapp.happypet.entry.CommentInfos;
import com.xindaoapp.happypet.entry.GoodsInfos;
import com.xindaoapp.happypet.fragments.ShoppingCartFragment;
import com.xindaoapp.happypet.ui.BaseActivity;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.share.SharePopupWindow;

/**
 * 商品详情
 * 
 * @author xindaoapp
 * 
 */
public class ProductDetailActivity extends BaseActivity implements ScrollTabHolder,
        ViewPager.OnPageChangeListener {
    private static AccelerateDecelerateInterpolator sSmoothInterpolator =
            new AccelerateDecelerateInterpolator();

    // private KenBurnsSupportView mHeaderPicture;
    private View mHeader;

    private PagerSlidingTabStrip mPagerSlidingTabStrip;
    private ViewPager mViewPager;
    private PagerAdapter mPagerAdapter;

    private int mActionBarHeight;
    private int mMinHeaderHeight;
    private int mHeaderHeight;
    private int mMinHeaderTranslation;
    private ViewPager mBannerViewPager;

    private final TypedValue mTypedValue = new TypedValue();
    private String productId;

    // 购物车商品数量
    private TextView cartsize;
    private ProductDetailActivityBroadCast broadCast;
    private SharePopupWindow win;
    private TextView title, price, shop_price;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mContext = ProductDetailActivity.this;

        super.onCreate(savedInstanceState);
        broadCast = new ProductDetailActivityBroadCast();
        registerReceiver(broadCast, new IntentFilter(Constants.DELETE_CART));
        loadDatas();
    }

    @Override
    protected void onResume() {
        if (UserState.isLogged()) {
            getCartNumber();
        }
        super.onResume();
    }

    private Product mProductInfos;
    private GoodsInfos mGoodsInfos;
    private CommentInfos mCommentInfos;

    private TextView product_detail_size_total;

    private TextView product_detail_size;

    @Override
    protected void initViews() {
        super.initViews();

        productId = getIntent().getStringExtra(Constants.KEY_GOODS_ID);

        product_detail_size_total = (TextView) findViewById(R.id.product_detail_size_total);
        product_detail_size = (TextView) findViewById(R.id.product_detail_size);
        cartsize = (TextView) findViewById(R.id.product_detail_cart_size);

        title = (TextView) findViewById(R.id.title);
        price = (TextView) findViewById(R.id.price);
        shop_price = (TextView) findViewById(R.id.shop_price);
        collection = findViewById(R.id.collection);

        findViewById(R.id.top_bar_right_imageview).setOnClickListener(mOnClickListener);
        findViewById(R.id.top_bar_right_share).setOnClickListener(mOnClickListener);
        collection.setOnClickListener(mOnClickListener);

        findViewById(R.id.addCart).setOnClickListener(mOnClickListener);
        findViewById(R.id.buyNow).setOnClickListener(mOnClickListener);
        findViewById(R.id.product_detail_cart).setOnClickListener(mOnClickListener);
        findViewById(R.id.rl_cart).setOnClickListener(mOnClickListener);

    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        unregisterReceiver(broadCast);
    }

    private void loadDatas() {
        HappyPetApplication.get().getMoccaApi()
                .getShopDetail(productId, UserState.getUserUid(), new IRequest<Product>() {

                    @Override
                    public void request(Product t) {
                        mProductInfos = t;
                        loadShopIntroInfo();
                    }
                });
    }

    private void loadShopIntroInfo() {
        HappyPetApplication.get().getMoccaApi()
                .getShopDetailInfo(productId, new IRequest<GoodsInfos>() {

                    @Override
                    public void request(GoodsInfos t) {
                        mGoodsInfos = t;
                        loadShopDetailComment();
                    }
                });
    }

    private void loadShopDetailComment() {
        HappyPetApplication
                .get()
                .getMoccaApi()
                .getShopDetailComment(productId, 0, 1, Constants.PAGE_SIZE,
                        new IRequest<CommentInfos>() {

                            @Override
                            public void request(CommentInfos t) {
                                mCommentInfos = t;
                                dataArrived();
                            }
                        });
    }

    private void dataArrived() {


        mMinHeaderHeight = getResources().getDimensionPixelSize(R.dimen.min_header_height);
        mHeaderHeight = getResources().getDimensionPixelSize(R.dimen.header_height);
        mMinHeaderTranslation = -mMinHeaderHeight + getActionBarHeight();
        // 处理Banner
        mBannerViewPager = (ViewPager) findViewById(R.id.viewpager);
        // mBannerViewPager.setLayoutParams(new
        // RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
        // CommonParameter.sScreenWidth * 308 / 640));


        if (mProductInfos != null) {
            onDataArrived(true);
            title.setText(mProductInfos.goods_name);
            price.setText("￥" + mProductInfos.shop_price);
            shop_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            shop_price.setText("￥" + mProductInfos.market_price);

            if (mProductInfos.is_collection == 1) {
                collection.setSelected(true);
            } else if (mProductInfos.is_collection == 0) {
                collection.setSelected(false);
            }



            mBannerViewPager.setAdapter(new PhotoAdapter(mProductInfos.img_url));


            product_detail_size_total.setText(mProductInfos.img_url.size() + "");

        } else {
            onDataArrivedEmpty();
        }



        // setContentView(R.layout.activity_main);

        // mHeaderPicture = (KenBurnsSupportView) findViewById(R.id.header_picture);
        // mHeaderPicture.setResourceIds(R.drawable.pic0, R.drawable.pic1);
        // mHeaderLogo = (ImageView) findViewById(R.id.header_logo);
        mHeader = findViewById(R.id.header);

        mPagerSlidingTabStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setOffscreenPageLimit(4);

        mPagerAdapter = new PagerAdapter(getSupportFragmentManager());
        mPagerAdapter.setTabHolderScrollingContent(this);

        mViewPager.setAdapter(mPagerAdapter);

        mPagerSlidingTabStrip.setViewPager(mViewPager);
        mPagerSlidingTabStrip.setOnPageChangeListener(this);



        mBannerViewPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                product_detail_size.setText((arg0 + 1) + "");
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });

    }



    @Override
    public void onPageScrollStateChanged(int arg0) {}

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

    @Override
    public void onPageSelected(int position) {
        SparseArrayCompat<ScrollTabHolder> scrollTabHolders = mPagerAdapter.getScrollTabHolders();
        ScrollTabHolder currentHolder = scrollTabHolders.valueAt(position);

        currentHolder
                .adjustScroll((int) (mHeader.getHeight() + ViewHelper.getTranslationY(mHeader)));
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
            int totalItemCount, int pagePosition) {
        if (mViewPager.getCurrentItem() == pagePosition) {
            int scrollY = getScrollY(view);
            ViewHelper.setTranslationY(mHeader, Math.max(-scrollY, mMinHeaderTranslation));
            float ratio =
                    clamp(ViewHelper.getTranslationY(mHeader) / mMinHeaderTranslation, 0.0f, 1.0f);
            // interpolate(mHeaderLogo, getActionBarIconView(),
            // sSmoothInterpolator.getInterpolation(ratio));
            setTitleAlpha(clamp(5.0F * ratio - 4.0F, 0.0F, 1.0F));
        }
    }

    @Override
    public void adjustScroll(int scrollHeight) {
        // nothing
    }

    public int getScrollY(AbsListView view) {
        View c = view.getChildAt(0);
        if (c == null) {
            return 0;
        }

        int firstVisiblePosition = view.getFirstVisiblePosition();
        int top = c.getTop();

        int headerHeight = 0;
        if (firstVisiblePosition >= 1) {
            headerHeight = mHeaderHeight;
        }

        return -top + firstVisiblePosition * c.getHeight() + headerHeight;
    }

    public static float clamp(float value, float max, float min) {
        return Math.max(Math.min(value, min), max);
    }


    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public int getActionBarHeight() {
        if (mActionBarHeight != 0) {
            return mActionBarHeight;
        }

        // if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
        // getTheme().resolveAttribute(android.R.attr.actionBarSize, mTypedValue, true);
        // } else {
        // getTheme().resolveAttribute(R.attr.actionBarSize, mTypedValue, true);
        // }

        mActionBarHeight =
                TypedValue.complexToDimensionPixelSize(mTypedValue.data, getResources()
                        .getDisplayMetrics());

        return mActionBarHeight;
    }

    /**
     * 切换viewpager
     */
    public void switchViewPager(int position) {
        mViewPager.setCurrentItem(position);
    }

    private void setTitleAlpha(float alpha) {}

    public class PagerAdapter extends FragmentPagerAdapter {

        private final SparseArrayCompat<ScrollTabHolder> mScrollTabHolders;
        private final String[] TITLES = {"商品详情", "产品规格", "商品评价"};
        private ScrollTabHolder mListener;

        public PagerAdapter(FragmentManager fm) {
            super(fm);
            mScrollTabHolders = new SparseArrayCompat<ScrollTabHolder>();
        }

        public void setTabHolderScrollingContent(ScrollTabHolder listener) {
            mListener = listener;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return TITLES[position];
        }

        @Override
        public int getCount() {
            return TITLES.length;
        }

        @Override
        public Fragment getItem(int position) {
            ScrollTabHolderFragment fragment =
                    (ScrollTabHolderFragment) ProductDetailFragment.newInstance(position,
                            mProductInfos, mGoodsInfos, mCommentInfos);

            mScrollTabHolders.put(position, fragment);
            if (mListener != null) {
                fragment.setScrollTabHolder(mListener);
            }

            return fragment;
        }

        public SparseArrayCompat<ScrollTabHolder> getScrollTabHolders() {
            return mScrollTabHolders;
        }

    }
    class PhotoAdapter extends android.support.v4.view.PagerAdapter {
        List<BigBanner> list;

        public PhotoAdapter(List<BigBanner> list) {
            this.list = list;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            ImageView view =
                    (ImageView) View.inflate(getBaseContext(), R.layout.item_viewpager_image, null);
            ImageLoader.getInstance().displayImage(list.get(position).url, view);

            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        ArrayList list1 = new ArrayList();
                        list1.add(list);
                        Intent intent =
                                new Intent(ProductDetailActivity.this, BigViewPageActivity.class);
                        intent.putStringArrayListExtra("list", list1);
                        intent.putExtra("current", position);
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            container.addView(view);
            return view;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public int getCount() {
            return list.size();
        }
    }


    private String isKill = "";
    private final OnClickListener mOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.addCart:// 加入购物车
                    if (isKill == null) {
                        isKill = "1";
                    }
                    if (mProductInfos != null) {
                        Intent add_cart =
                                new Intent(ProductDetailActivity.this, ProductAddActivity.class);
                        mProductInfos.is_activity = "0";// 立即购买
                        add_cart.putExtra("pro", mProductInfos);
                        add_cart.putExtra("isKill", isKill);
                        startActivity(add_cart);
                    } else {
                        Toast.makeText(getApplicationContext(), "获取商品信息失败", Toast.LENGTH_SHORT)
                                .show();
                    }
                    break;
                case R.id.buyNow:// 立即购买
                    if (isKill == null) {
                        isKill = "1";
                    }
                    Intent nowbuy =
                            new Intent(ProductDetailActivity.this, ProductAddActivity.class);
                    mProductInfos.is_activity = "1";// 立即购买
                    nowbuy.putExtra("pro", mProductInfos);
                    // nowbuy.putExtra("nowbuy", "1");
                    nowbuy.putExtra("isKill", isKill);
                    startActivity(nowbuy);
                    break;
                case R.id.rl_cart:
                case R.id.top_bar_right_imageview:// 购物车
                    if (UserState.isLogged(ProductDetailActivity.this)) {
                        Intent mainIntent =
                                new Intent(ProductDetailActivity.this, MainActivity.class);
                        mainIntent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                                ShoppingCartFragment.class.getCanonicalName());
                        startActivity(mainIntent);
                    }

                    break;
                case R.id.top_bar_right_share:// 分享
                    if (mProductInfos == null) {
                        return;
                    }
                    String s = "http://ts.leepet.com/share/index.html?id=" + productId;
                    win = new SharePopupWindow(mProductInfos.thumb_url.get(0).url);
                    win.setDefaultIconId(R.drawable.icon);

                    String SinaContent =
                            String.format(
                                    "#尾巴圈宠物# 在尾巴圈发现了很不错的的宠物用品“%1$s”，还有更多海量商品供选择！@尾巴圈 ，我的养宠神器！下载地址>>%2$s",
                                    s, getResources().getString(R.string.app_download_url));
                    String WXContent = String.format("%s", mProductInfos.goods_name);
                    String QQContent = String.format("%s", mProductInfos.goods_name);

                    win.setInfors(ProductDetailActivity.this, SinaContent, "尾巴圈，我的养宠神器",
                            SinaContent, WXContent, QQContent, s).showAtLocation(
                            ProductDetailActivity.this.findViewById(R.id.bottom), Gravity.BOTTOM,
                            0, 0);

                    // win.setInfors(
                    // ProductDetailActivity.this,
                    // String.format("我在 @尾巴圈客户端上发现了“%1$s，很不错，推荐给你们。” %2$s",
                    // mProductInfos.goods_name, s), mProductInfos.goods_name,
                    // mProductInfos.goods_name, s).showAtLocation(
                    // ProductDetailActivity.this.findViewById(R.id.bottom), Gravity.BOTTOM,
                    // 0, 0);

                    CommonUtil.addScreenBg(win, ProductDetailActivity.this);
                    break;

                case R.id.collection:// 收藏
                    if (UserState.isLogged(ProductDetailActivity.this)) {
                        if (mProductInfos != null) {
                            getCollectData();
                        } else {
                            Toast.makeText(getApplicationContext(), "获取商品信息失败", Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }
                    break;
            }
        }
    };

    private View collection;

    private Context mContext;

    private void getCollectData() {// 获取收藏数据
        if (CommonUtil.checkNetState(ProductDetailActivity.this)) {
            final RequestParams params = new RequestParams();
            params.put("userID", UserState.getUserUid());
            params.put("goodsID", productId);
            if (collection.isSelected()) {// 取消
                AddClient.get(Address.DEL_COLLECTION, params, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, String content) {
                        int result = -1;
                        JSONObject obj;
                        try {
                            obj = new JSONObject(content);
                            result = obj.getInt("status");

                            if (result == 1) {// 说明没有赞
                                Toast.makeText(mContext, "取消收藏成功", Toast.LENGTH_SHORT).show();
                                collection.setSelected(false);
                                sendBroadcast(new Intent(Constants.SHOP_COLLECT));
                            } else {
                                Toast.makeText(mContext, "取消收藏失败", Toast.LENGTH_SHORT).show();
                                collection.setSelected(true);
                            }
                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Throwable arg0, String arg1) {
                        super.onFailure(arg0, arg1);
                        Toast.makeText(mContext, R.string.get_error_data, 0).show();
                    }
                });
            } else {
                AddClient.get(Address.ADD_COLLECTION, params, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, String content) {
                        int result = -1;
                        JSONObject obj;
                        try {
                            obj = new JSONObject(content);
                            result = obj.getInt("status");
                            if (result == 1) {// 说明没有赞
                                Toast.makeText(mContext, "添加收藏成功", Toast.LENGTH_SHORT).show();
                                collection.setSelected(true);
                            } else {
                                Toast.makeText(mContext, "添加收藏失败", Toast.LENGTH_SHORT).show();
                                collection.setSelected(false);
                            }
                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Throwable arg0, String arg1) {
                        super.onFailure(arg0, arg1);
                        Toast.makeText(mContext, R.string.get_error_data, 0).show();
                    }
                });
            }

        } else {
            Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
            return;
        }
    }


    private void getCartNumber() {
        if (CommonUtil.checkNetState(ProductDetailActivity.this)) {
            RequestParams params = new RequestParams();
            params.put("userID", CommonUtil.decode(UserState.getUserUid()));
            params.add("version", "1.0");
            AddClient.get(Address.GET_CARTNUMBER, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, String content) {
                    String data = null;
                    JSONObject obj;
                    try {
                        obj = new JSONObject(content);
                        data = obj.getString("data");
                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }
                    String count = null;
                    JSONObject obj1;
                    try {
                        obj1 = new JSONObject(data);
                        count = obj1.getString("count");
                        if (Integer.parseInt(count) > 0) {
                            if (cartsize.getVisibility() == View.GONE) {
                                cartsize.setVisibility(View.VISIBLE);
                            }
                            cartsize.setText(count);
                        }
                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Throwable error, String content) {
                    super.onFailure(error, content);
                }
            });
        } else {
            Toast.makeText(ProductDetailActivity.this, R.string.pLease_check_network, 0).show();
            return;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null != win) {
            UMSsoHandler ssoHandler = win.mController.getConfig().getSsoHandler(requestCode);
            if (ssoHandler != null) {
                ssoHandler.authorizeCallBack(requestCode, resultCode, data);
            }
        }
    }


    private class ProductDetailActivityBroadCast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            int goods_num = intent.getIntExtra("goods_number", -1);
            if (goods_num == -1) {
                return;
            } else {
                // int cart_num = Integer.parseInt(cart.getText().toString()) -
                // goods_num;
                if (goods_num > 0) {
                    cartsize.setText(goods_num + "");
                } else {
                    if (cartsize.getVisibility() == View.VISIBLE) {
                        cartsize.setText("0");
                        cartsize.setVisibility(View.GONE);
                    }
                }
            }
        }
    }

    @Override
    protected int getContentViewResId() {
        return R.layout.activity_shop_detail;
    }

    @Override
    protected int getTopBarLeftImageViewRes() {
        return R.drawable.top_bar_back;
    }

    // @Override
    // protected int getTopBarRightImageViewRes() {
    // return R.drawable.cart_shop;
    // }


    @Override
    protected OnClickListener getLeftViewClickListener() {
        return new OnClickListener() {
            @Override
            public void onClick(View v) {
                ProductDetailActivity.this.finish();
            }
        };
    }

}
